<template>
  <view class="time">
   <view class="time__custom" v-if="days > 0"> <text class="time__custom__item">{{ days }}</text></view>
	<text class="time__doc" v-if="days > 0">天</text>
    <view class="time__custom"><text class="time__custom__item">{{ hours }}</text></view>
	<text class="time__doc">时</text>
    <view class="time__custom"><text class="time__custom__item">{{ minutes }}</text></view>
	<text class="time__doc">分</text>
    <view class="time__custom"><text class="time__custom__item">{{ seconds }}</text></view>
	<text class="time__doc">秒</text>
  </view>
</template>
 

<script>
export default {
  data() {
    return {
      endTime: "2025-02-27 11:00:00", // 这个值应该从接口获取
      timer: null,
      days: '0',
      hours: '00',
      minutes: '00',
      seconds: '00'
    }
  },
  created() {
    // 在实际项目中，你可能需要先调用接口获取 endTime
    // 获取到 endTime 后再调用 startCountDown
    this.startCountDown()
  },
  methods: {
    startCountDown() {
      // 清除可能存在的旧定时器
      if (this.timer) {
        clearInterval(this.timer)
      }

      this.timer = setInterval(() => {
        const end = new Date(this.endTime).getTime()
        const now = new Date().getTime()
        const diff = end - now

        if (diff <= 0) {
          // 倒计时结束
          clearInterval(this.timer)
          this.days = '0'
          this.hours = '00'
          this.minutes = '00'
          this.seconds = '00'
          // 可以在这里添加倒计时结束后的处理逻辑
          this.$emit('timeUp')
          return
        }

        // 计算天数、小时数、分钟数和秒数
        this.days = Math.floor(diff / (1000 * 60 * 60 * 24)).toString()
        this.hours = this.padZero(Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)))
        this.minutes = this.padZero(Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)))
        this.seconds = this.padZero(Math.floor((diff % (1000 * 60)) / 1000))
      }, 1000)
    },
    // 补零函数
    padZero(num) {
      return num < 10 ? '0' + num : num.toString()
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
.countdown {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}
	.time{
				display: flex;
				align-items: center;
				justify-content: center;
				margin-top: 36rpx;
				.time__custom{
					width: 60rpx;
					height: 56rpx;
					background: #020202;
					border-radius: 2rpx;
					text-align: center;
					line-height: 56rpx;
					color: #fff;
					font-size: 28rpx;
				}
				.time__doc{
					color: #020202;
					margin: 0 10rpx;
					font-size: 28rpx;
				}
			}
</style>